from pml import PML
from pml import Objects

class InStream(Objects.object.typeobject):
    def __init__(self):
        super().__init__('InStream')
        self.buffer = ''

    def getObject(self):
        self.methods['getc'] = self.getc
        self.methods['gets'] = self.gets
        self.methods['next'] = self.next

        return self

    def input(self, frame):
        return frame.stdio.get(frame, frame.stdio, None).obj.value + '\n'
    def getChar(self):
        if len(self.buffer):
            ret = self.buffer[0]
            self.buffer = self.buffer[1:]
            return ret
        else:
            raise Exception

    @staticmethod
    def getc(frame, this, position):
        try:
            return PML.object.ChangeObject.PMLString_FromStr(this.getChar())
        except Exception:
            this.buffer = this.input(frame)
            this.getc(frame, this, position)

    @staticmethod
    def gets(frame, this, position):
        if not this.buffer.__len__():
            this.buffer = this.input(frame)
        ret = ''
        temp = ''
        while temp not in '\n \t' or temp == '':
            ret += temp
            try:
                temp = this.getChar()
            except Exception:
                this.buffer = this.input(frame)
                temp = this.getChar()
        this.buffer = ' ' + this.buffer
        return PML.object.ChangeObject.PMLString_FromStr(ret)

    @staticmethod
    def next(frame, this, position):
        this.buffer = this.buffer[1:]

class OutStream(Objects.object.typeobject):
    def __init__(self):
        super().__init__()
        self.buffer = ''

PML_MODULE = PML.module.ModuleSetup(variablesOrFunctions={
    'In': InStream().getObject()
}, constants={})
